<?php

class AdminController extends Controller {
    
    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array(
                    'feedback', 'done', 'ShipTo', 'ShipToDetail', 'ExportShipDetail',
                    'ExportShipDetailByDate', 'ProductGroup','ProductGroupAdd','ProductGroupUpdate',
                    'AddItem','GetProduct','DeleteItem','GetDes', 'AddPhoto',
                    'ImportPhoto', 'ExportGroup', 'AddMulti', 'DeleteXls','nid',
                    'nidUpdate'
                ),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    
    function actionIndex() {
        $this->render('index');
    }

    function actionFeedback() {
        $criteria = new CDbCriteria();
        $criteria->order = 't.fid asc';
        $criteria->with = 'pricing';
        $criteria->addCondition("t.status=1");

        $search['Date'] = $_REQUEST['Date'];
        $search['ProductModel'] = $_REQUEST['ProductModel'];        
        $search['ProductDetail'] = $_REQUEST['ProductDetail'];
        $search['Buyer'] = $_REQUEST['Buyer'];
        $search['Destination1'] = $_REQUEST['Destination1'];
        $search['ReceiptNo'] = $_REQUEST['ReceiptNo'];
        $search['s'] = $_REQUEST['s'];
        $search['e'] = $_REQUEST['e'];        

        if ($search['Date']) {
            $criteria->addCondition("pricing.Date = '" . $search['Date'] . "'");
        }
        if ($search['ProductModel']) {
            $criteria->addCondition("[pricing].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['ProductDetail']) {
            $criteria->addCondition("[pricing].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }
        if ($search['Buyer']) {
            $criteria->addCondition("[pricing].Buyer like '%" . $search['Buyer'] . "%'");
        }
        if ($search['Destination1']) {
            $criteria->addCondition("[pricing].Destination1='".$search['Destination1']."'");
        }
        if ($search['ReceiptNo']) {
            $criteria->addCondition("[pricing].ReceiptNo like '%" . $search['ReceiptNo'] . "%'");
        }
        if ($search['s']) {
            $criteria->addCondition("t.dateline>='" . $search['s'] . "'");
        }
        if ($search['e']) {
            $criteria->addCondition("t.dateline<'" . $search['e'] . "'");
        }

        $count = IteamFeedback::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = IteamFeedback::model()->findAll($criteria);
        $this->render('feedback', array(
            'rowTable' => $rowTable,
            'search' => $search,
            'pages' => $pager
        ));
    }
    
    //处理
    public function actionDone(){
        $fid = $_REQUEST['fid'];
        $model = IteamFeedback::model()->findByPk($fid);
        if($model){
            $model->status=2;
            if($model->save()){
                $msg = '更新成功';
            }else{
                $msg = '更新失败';
            }
        }else{
            $msg = '参数错误';
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }
    
    //包裹查询
    public function actionShipTo(){
        $this->layout = 'column2';
        $criteria = new CDbCriteria();
        $criteria->order = 'ShipDate desc,t.Tracking desc';
        $criteria->select = 'distinct ShippingNumber,Tracking,ServiceType,ShipDate,DeliveryDate';
        $criteria->addCondition("BuySell='Buy'");
        $criteria->addCondition("Tracking<>''");
//        $criteria->with = 'pricing';

        $search['Tracking'] = $_REQUEST['Tracking'];
        $search['ServiceType'] = $_REQUEST['ServiceType'];        
        $search['s'] = $_REQUEST['s'];
        $search['e'] = $_REQUEST['e'];

        if ($search['ServiceType']) {
            $criteria->addCondition("t.ServiceType = '" . $search['ServiceType'] . "'");
        }
        if ($search['Tracking']) {
            $criteria->addCondition("t.Tracking = '" . $search['Tracking'] . "'");
        }
        if ($search['s']) {
            $criteria->addCondition("t.ShipDate>='" . $search['s'] . "'");
        }
        if ($search['e']) {
            $criteria->addCondition("t.ShipDate<'" . $search['e'] . "'");
        }
        
        $labels = ShipTo::model()->attributeLabels();

        $count = ShipTo::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = ShipTo::model()->findAll($criteria);
        $this->render('shipTo', array(
            'rowTable' => $rowTable,
            'search' => $search,
            'pages' => $pager,
            'labels' => $labels,
        ));
    }
    
    //包裹查询详情
    public function actionShipToDetail($tracking){
        $this->layout = 'column2';        
        
        $criteria = new CDbCriteria();
        $criteria->order = 't.[Index] desc';
        $criteria->with = 'ship';
        $criteria->addCondition("ship.BuySell='Buy'");
        $criteria->addCondition("ship.Tracking='".$tracking."'");        
        
        $rowTable = ShippingDetails::model()->findAll($criteria);
        unset($criteria);
        $this->render('shipToDetail', array(
            'rowTable' => $rowTable,
            'tracking'=>$tracking,
        ));
    }
    
    //导出shipDetail
    public function actionExportShipDetail($tracking) {
        $criteria = new CDbCriteria();
        $criteria->order = 't.[Index] desc';
        $criteria->with = 'ship';
        $criteria->addCondition("ship.BuySell='Buy'");
        $criteria->addCondition("ship.Tracking='".$tracking."'"); 
        $rowTable = ShippingDetails::model()->findAll($criteria);
        unset($criteria);
        
        foreach($rowTable as &$item){
            if ($item->ProductID) {
                $item->ProductName = $item->product->ProductDetail;
            }
        }

        spl_autoload_unregister(array('YiiBase', 'autoload'));
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel.php');
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel/IOFactory.php');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '货柜编号（快递编号）')
                ->setCellValue('B1', '产品编号')
                ->setCellValue('C1', '产品细节')
                ->setCellValue('D1', '订购数量')
                ->setCellValue('E1', '运出数量');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);

        $i = 2;
        foreach ($rowTable as $item) {
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('B' . $i, $item->ProductModel)
                    ->setCellValue('C' . $i, $item->ProductName)
                    ->setCellValue('D' . $i, $item->OrderQuantity)
                    ->setCellValue('E' . $i, $item->ShipmentQuantity);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$i, $item->ship->Tracking, PHPExcel_Cell_DataType::TYPE_STRING);
            $i++;
        }

        $filename = 'ShipDetail_'.$tracking.'.xls';
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename=' . urlencode($filename) . '');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        spl_autoload_register(array('YiiBase', 'autoload'));
    }
    
    //根据日期导出包裹内容
    public function actionExportShipDetailByDate(){
        $criteria = new CDbCriteria();
        $criteria->order = 't.Tracking desc';
        $criteria->select = 'distinct Tracking';
        $criteria->addCondition("BuySell='Buy'");
        $criteria->addCondition("Tracking<>''");
//        $criteria->with = 'pricing';
     
        $search['Tracking'] = $_REQUEST['Tracking'];
        $search['ServiceType'] = $_REQUEST['ServiceType'];        
        $search['s'] = $_REQUEST['s'];
        $search['e'] = $_REQUEST['e'];

        if ($search['ServiceType']) {
            $criteria->addCondition("t.ServiceType = '" . $search['ServiceType'] . "'");
        }
        if ($search['Tracking']) {
            $criteria->addCondition("t.Tracking = '" . $search['Tracking'] . "'");
        }
        if ($search['s']) {
            $criteria->addCondition("t.ShipDate>='" . $search['s'] . "'");
        }
        if ($search['e']) {
            $criteria->addCondition("t.ShipDate<'" . $search['e'] . "'");
        }

        $rowTable = ShipTo::model()->findAll($criteria);
        unset($criteria);
        
        $trackingArr = CHtml::listData($rowTable,'Tracking', 'Tracking');
        unset($rowTable);
        
        $condition = new CDbCriteria();
        $condition->with = 'ship';
        $condition->addCondition("ship.BuySell='Buy'");
        $condition->addInCondition('ship.Tracking', $trackingArr);
        $rowTable = ShippingDetails::model()->findAll($condition);
        unset($condition);
        
        foreach($rowTable as &$item){
            if ($item->ProductID) {
                $item->ProductName = $item->product->ProductDetail;
            }
            $item->Inventory = $item->ship->ShipDate;//借用一下Inventory存个运出日期    
        }
        spl_autoload_unregister(array('YiiBase', 'autoload'));
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel.php');
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel/IOFactory.php');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '货柜编号（快递编号）')
                ->setCellValue('B1', '产品编号')
                ->setCellValue('C1', '产品细节')
                ->setCellValue('D1', '订购数量')
                ->setCellValue('E1', '运出数量')
                ->setCellValue('F1', '运出时间');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $i = 2;
        foreach ($rowTable as $item) {
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('B' . $i, $item->ProductModel)
                    ->setCellValue('C' . $i, $item->ProductName)
                    ->setCellValue('D' . $i, $item->OrderQuantity)
                    ->setCellValue('E' . $i, $item->ShipmentQuantity)
                    ->setCellValue('F' . $i, $item->Inventory);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$i, $item->ship->Tracking, PHPExcel_Cell_DataType::TYPE_STRING);
            $i++;
        }

        $filename = 'ShipDetail.xls';
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename=' . urlencode($filename) . '');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        spl_autoload_register(array('YiiBase', 'autoload'));
    }


    //产品组合管理
    public function actionProductGroup(){
        $type = $_REQUEST['type'];
        if($type!=2){
            $type=1;
            $title = '产品组合列表';
        }else{
            $title = '多颜色记录列表';
        }
        
        $this->layout = 'column2';
        $criteria = new CDbCriteria();
        $criteria->order = 'updated desc,groupId desc';
        $criteria->addCondition('groupType='.$type);

        $search['groupName'] = $_REQUEST['groupName'];
        $search['groupTitle'] = $_REQUEST['groupTitle'];
        $search['creator'] = $_REQUEST['creator'];
        $search['editor'] = $_REQUEST['editor'];
        $search['s'] = $_REQUEST['s'];
        $search['e'] = $_REQUEST['e'];

        if ($search['groupName']) {
            $criteria->addCondition("t.groupName = '" . $search['groupName'] . "'");
        }
        if ($search['groupTitle']) {
            $criteria->addCondition("t.groupTitle like '%" . $search['groupTitle'] . "%'");
        }        
        if ($search['creator']) {
            $criteria->addCondition("t.creator = '" . $search['creator'] . "'");
        }
        if ($search['editor']) {
            $criteria->addCondition("t.editor = '" . $search['editor'] . "'");
        }
        if ($search['s']) {
            $criteria->addCondition("t.updated>='" . $search['s'] . "'");
        }
        if ($search['e']) {
            $criteria->addCondition("t.updated<'" . $search['e'] . "'");
        }
        
        $labels = IteamGroup::model()->attributeLabels();

        $count = IteamGroup::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = IteamGroup::model()->findAll($criteria);
        $this->render('group', array(
            'rowTable' => $rowTable,
            'search' => $search,
            'pages' => $pager,
            'labels' => $labels,
            'title' => $title,
        ));
    }
    
    //新增产品组合
    public function actionProductGroupAdd(){
        $type = $_REQUEST['type'];
        if($type!=2){
            $type=1;
            $view = 'create';
        }else{
            $view = 'createMulti';
        }
        $this->layout = 'column2';
        $model = new IteamGroup;
        
        $model->groupType=$type;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['IteamGroup'])) {
            $model->attributes = $_POST['IteamGroup'];
    
            if ($model->save()) {
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("添加成功");window.location.href="'.Yii::app()->createUrl('admin/productGroupUpdate',array('groupId'=>$model->groupId,'type'=>$type)).'";</script>';
            }
        }

        $this->render($view, array(
            'model' => $model,
        ));
    }
    
    //产品组合详情
    public function actionProductGroupUpdate($groupId){
        $this->layout = 'column2';
        $model = IteamGroup::model()->findByPk((int)$groupId);
        
        if (isset($_POST['IteamGroup'])) {
            $model->attributes = $_POST['IteamGroup'];
    
            if ($model->save()) {
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("更新成功");window.location.href="'.Yii::app()->createUrl('admin/productGroupUpdate',array('groupId'=>$model->groupId)).'";</script>';
            }
        }
        
        if ($model->groupType!=2){
            $view = 'update';
        }else{
            $view = 'updateMulti';
        }

        $this->render($view, array(
            'model' => $model,
        ));
    }
    
    //group关联product
    public function actionAddItem($groupId){
        $this->layout = 'pop';
        
        if($_REQUEST['groupItemId']){
            $model = IteamGroupItem::model()->findByPk((int)$_REQUEST['groupItemId']);
        }
        
        if(!$model){
            $model = new IteamGroupItem;
        }else{
            $model->productId = $model->product->ProductModel;
        }
        
        $model->groupId = $groupId;
        
        if (isset($_POST['IteamGroupItem'])) {
            $model->attributes = $_POST['IteamGroupItem'];
    
            $product = Product::model()->find("ProductModel='$model->productId'");            
            $model->productId = $product->ProductID;
            
            //判断一下如果是添加，如果这个group中已经有这个产品了，就更新下，不允许重复关联
            if($model->isNewRecord){
                $condition = new CDbCriteria();
                $condition->addCondition('groupId='.$model->groupId);
                $condition->addCondition('productId='.$model->productId);
                $have = IteamGroupItem::model()->find($condition);
                unset($condition);
                
                if($have){
                    header("Content-Type:text/html;charset=utf-8");
                    echo '<script>alert("产品已存在");parent.$.fancybox.close();</script>';
                    exit;
                }
            }
            
            if ($model->save()) {
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("更新成功");parent.$.fancybox.close();</script>';
            }
        }
        
        $this->render('addItem', array(
            'model' => $model,
        ));
    }
    
    //autocomplete用的获取产品
    public function actionGetProduct($q){
        $condition = new CDbCriteria();
        if($q){
            $condition->addCondition("ProductModel like'%$q%'");
        }
        $rowTable = Product::model()->findAll($condition);
        unset($condition);
        foreach($rowTable as $row){
            echo "$row->ProductModel|[$row->ProductModel]$row->ProductDetail\n";
        }
    }
    
    //删除groupItem
    public function actionDeleteItem($id){
        $model = IteamGroupItem::model()->findByPk((int)$id);
        $groupId = $model->groupId;
        $model->delete();
        header("Content-Type:text/html;charset=utf-8");
        echo '<script>alert("删除成功");window.location.href="'.Yii::app()->createUrl('admin/productGroupUpdate',array("groupId"=>$groupId)).'";</script>';
    }
    
    //获取内容集合
    public function actionGetDes(){
        $feild=$_REQUEST['feild'];
        $gid=$_REQUEST['gid'];
        $groupItems = IteamGroupItem::model()->findAll('groupId='.(int)$gid);
        foreach($groupItems as $item){
            $msg = $msg.$item->product->$feild.'<br /><br />';
        }
        echo CJSON::encode(array('success' => true, 'msg' => $msg));
    }
    
    //group关联photo
    public function actionAddPhoto($groupId){
        $this->layout = 'pop';
        
        if($_REQUEST['photoId']){
            $model = IteamGroupPhoto::model()->findByPk((int)$_REQUEST['photoId']);
        }
        
        if(!$model){
            $model = new IteamGroupPhoto;
        }
        
        $model->groupId = $groupId;
        
        if (isset($_POST['IteamGroupPhoto'])) {
            $model->attributes = $_POST['IteamGroupPhoto'];

            if ($model->save()) {
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("更新成功");parent.$.fancybox.close();</script>';
            }
        }
        
        $this->render('addPhoto', array(
            'model' => $model,
        ));
    }
    
    //删除groupPhoto
    public function actionDeletePhoto($id){
        $model = IteamGroupPhoto::model()->findByPk((int)$id);
        $groupId = $model->groupId;
        $model->delete();
        header("Content-Type:text/html;charset=utf-8");
        echo '<script>alert("删除成功");window.location.href="'.Yii::app()->createUrl('admin/productGroupUpdate',array("groupId"=>$groupId)).'";</script>';
    }
    
    //从子产品中导入图片
    public function actionImportPhoto($groupId){
        $this->layout = 'pop';
        
        $rowTable = IteamGroupItem::model()->findAll('groupId='.$groupId);
        
        if($rowTable){
            $condition = new CDbCriteria();
            $condition->addInCondition('ProductID', CHtml::listData($rowTable, 'productId', 'productId'));
            $products = Product::model()->findAll($condition);
            unset($condition);
            if($products){
                $condition = new CDbCriteria();
                $condition->addInCondition('ProductNo', CHtml::listData($products, 'ProductModel', 'ProductModel'));
                $photos = Photo::model()->findAll($condition);
                unset($condition);
            }
        }
        
        if (isset($_POST['url'])) {
            $urls = $_POST['url'];
            if($urls){
                foreach($urls as $url){
                    $condition = new CDbCriteria();
                    $condition->addCondition("path='".$url."'");
                    $have = IteamGroupPhoto::model()->find($condition);
                    unset($condition);
                    if(!$have){
                        $model = new IteamGroupPhoto;
                        $model->path = $url;
                        $model->groupId = $groupId;
                        $model->save();
                        unset($model);
                    }
                }
            }
            header("Content-Type:text/html;charset=utf-8");
            echo '<script>alert("更新成功");parent.$.fancybox.close();</script>';
        }
       
        $this->render('import', array(
            'rowTable' => $photos,
        ));
    }
    
    //导出组合
    public function actionExportGroup(){        
        $criteria = new CDbCriteria();
        $criteria->order = 'groupType asc,updated desc,groupId desc';
        $criteria->addCondition('groupType=1');

        $search['groupName'] = $_REQUEST['groupName'];
        $search['groupTitle'] = $_REQUEST['groupTitle'];
        $search['creator'] = $_REQUEST['creator'];
        $search['editor'] = $_REQUEST['editor'];
        $search['s'] = $_REQUEST['s'];
        $search['e'] = $_REQUEST['e'];
        
        $search['groupId'] = $_REQUEST['groupId'];

        if ($search['groupName']) {
            $criteria->addCondition("t.groupName = '" . $search['groupName'] . "'");
        }
        if ($search['groupTitle']) {
            $criteria->addCondition("t.groupTitle like '%" . $search['groupTitle'] . "%'");
        }        
        if ($search['creator']) {
            $criteria->addCondition("t.creator = '" . $search['creator'] . "'");
        }
        if ($search['editor']) {
            $criteria->addCondition("t.editor = '" . $search['editor'] . "'");
        }
        if ($search['s']) {
            $criteria->addCondition("t.updated>='" . $search['s'] . "'");
        }
        if ($search['e']) {
            $criteria->addCondition("t.updated<'" . $search['e'] . "'");
        }
        
        if ($search['groupId']) {
            $criteria->addInCondition("groupId", $search['groupId']);
        }        
        $rowTable = IteamGroup::model()->findAll($criteria);
        
        $keywords = array();
        foreach($rowTable as $row){
            $temp = array();
            if($row->products)
            $temp['productName'] = implode('+', CHtml::listData($row->products2, 'ProductName', 'ProductName'));
            $temp['productModel'] = 'group_'.$row->groupName;
            $temp['quantity'] = $row->groupNumber;
            $temp['title'] = $row->groupTitle;
            $keywords[] = $temp;
        }
        
        spl_autoload_unregister(array('YiiBase', 'autoload'));
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel.php');
        include_once(dirname(dirname(__FILE__)) . '/extensions/PHPExcel/IOFactory.php');
        
        //判断文件是否存在
        $filename = Yii::app()->user->name.'_keywords.xls';
        $path = Yii::app()->params['groupPath'];
        if(file_exists($path.'\\'.$filename)){
            $objPHPExcel = PHPExcel_IOFactory::load($path.'\\'.$filename);           //导入上传的excel文件的数据逻辑
            $ActSheet = $objPHPExcel->getActiveSheet(0);                                               //获取excel中sheet(0)的数据

            $allRow = $ActSheet->getHighestRow();
            //读取数据
            $dataArr = array();
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $dataRow = array();
                $dataRow['productName'] = $ActSheet->getCell('B' . $currentRow)->getValue();
                $dataRow['productModel'] = $ActSheet->getCell('C' . $currentRow)->getValue();
                $dataRow['quantity'] = $ActSheet->getCell('D' . $currentRow)->getValue();
                $dataRow['title'] = $ActSheet->getCell('I' . $currentRow)->getValue();
                $dataArr[] = $dataRow;
                unset($dataRow);
            }
        }
        
        if($dataArr){
            foreach ($keywords as $key){
                $dataArr[] = $key;
            }
            $keywords = $dataArr;
        }
        
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'ID')
                ->setCellValue('B1', 'Product Name')
                ->setCellValue('C1', 'Product NO.')
                ->setCellValue('D1', 'Quantity')
                ->setCellValue('E1', 'Category')
                ->setCellValue('F1', 'Color')
                ->setCellValue('G1', 'Size')
                ->setCellValue('H1', 'Item Type')
                ->setCellValue('I1', 'Title')
                ->setCellValue('J1', 'Search Terms1')
                ->setCellValue('K1', 'Search Terms2')
                ->setCellValue('L1', 'Search Terms3')
                ->setCellValue('M1', 'Search Terms4')
                ->setCellValue('N1', 'Search Terms5')
                ->setCellValue('O1', 'Platform')
                ->setCellValue('P1', 'Finished Date')
                ->setCellValue('Q1', 'Person')
                ->setCellValue('R1', 'Remark')
                ->setCellValue('S1', 'Old Title')
                ->setCellValue('T1', 'Used Or Not')
                ->setCellValue('U1', 'Listing Date');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(10);
        $i = 2;
        foreach ($keywords as $item) {
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('B' . $i, $item['productName'])
                    ->setCellValue('C' . $i, $item['productModel'])
                    ->setCellValue('D' . $i, $item['quantity'])
                    ->setCellValue('I' . $i, $item['title']);
            $i++;
        }
        //保存并输出
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save($path.'\\'.$filename);
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename=' . $filename . '');
        header('Cache-Control: max-age=0');        
        $objWriter->save('php://output');
        spl_autoload_register(array('YiiBase', 'autoload'));
    }
    
    //多颜色记录关联product
    public function actionAddMulti($groupId){
        $this->layout = 'pop';
        
        if ($_POST['productIds']) {
            $msg = '';
            foreach($_POST['productIds'] as $productId){
                $model = new IteamGroupItem;
                $model->productId = $productId;
                $model->groupId = $groupId;
                $model->save();
            }
            header("Content-Type:text/html;charset=utf-8");
            echo '<script>alert("关联成功");</script>';
        }
        
        $group = IteamGroup::model()->findByPk($groupId);

        $criteria = new CDbCriteria();
        $criteria->order = 't.ProductID desc';
        $criteria->addCondition("Type='MX'");
        $criteria->addNotInCondition('ProductID', CHtml::listData($group->products, 'productId', 'productId'));

        $search['ProductModel'] = $_REQUEST['ProductModel'];
        $search['ProductName'] = $_REQUEST['ProductName'];
        $search['ProductDetail'] = $_REQUEST['ProductDetail'];
        $search['NIDNo'] = $_REQUEST['NIDNo'];

        if ($search['ProductModel']) {
            $criteria->addCondition("[t].[ProductModel] like '%" . $search['ProductModel'] . "%'");
        }
        if ($search['ProductName']) {
            $criteria->addCondition("[t].[ProductName] like '%" . $search['ProductName'] . "%'");
        }
        if ($search['ProductDetail']) {
            $criteria->addCondition("[t].[ProductDetail] like '%" . $search['ProductDetail'] . "%'");
        }
        if ($search['NIDNo']) {
            $criteria->addCondition("[t].[NIDNo] like '%" . $search['NIDNo'] . "%'");
        }

        $labels = Product::model()->attributeLabels();
        
        $count = Product::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = Product::model()->findAll($criteria);
        $this->render('multi', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }
    
    public function actionDeleteXls(){
        $filename = Yii::app()->user->name.'_keywords.xls';
        $path = Yii::app()->params['groupPath'];
        if(file_exists($path.'\\'.$filename)){
            $file = Yii::app()->file->set($path.'\\'.$filename, true);
            $file->delete();
        }
        header("Content-Type:text/html;charset=utf-8");
        echo '<script>alert("删除成功");window.location.href="'.Yii::app()->createUrl('admin/productGroup').'"</script>';
    }
    
    //nid列表
    public function actionNid(){
        $criteria = new CDbCriteria();
        $criteria->order = 'Rank,t.[Index] desc';
        $criteria->addCondition("SubStatus='New Item'");

        $search['NIDNum'] = $_REQUEST['NIDNum'];
        $search['CheckPerson'] = $_REQUEST['CheckPerson'];
        $search['Category'] = $_REQUEST['Category'];
        $search['SubCategory'] = $_REQUEST['SubCategory'];
        $search['RCMDReason'] = trim($_REQUEST['RCMDReason']);
        $search['Date'] = $_REQUEST['Date'];

        if ($search['NIDNum']) {
            $criteria->addCondition("t.NIDNum like '%" . $search['NIDNum'] . "%'");
        }
        if ($search['CheckPerson']) {
            $criteria->addCondition("t.CheckPerson like '%" . $search['CheckPerson'] . "%'");
        }
        if ($search['Category']) {
            $criteria->addCondition("t.Category like '%" . $search['Category'] . "%'");
        }
        if ($search['SubCategory']) {
            $criteria->addCondition("t.SubCategory like '%" . $search['SubCategory'] . "%'");
        }
        if ($search['RCMDReason']) {
            $criteria->addCondition("t.RCMDReason like '%" . $search['RCMDReason'] . "%'");
        }
        if ($search['Date']) {
            $criteria->addCondition("t.Date='" . $search['Date'] . "'");
        }

        $labels = NID::model()->attributeLabels();

        $count = NID::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = 10;
        $pager->applyLimit($criteria);
        $rowTable = NID::model()->findAll($criteria);
        $this->render('nid', array('rowTable' => $rowTable, 'search' => $search, 'pages' => $pager, 'labels' => $labels));
    }
    
    //添加Nid
    public function actionNidUpdate(){
        $index = $_REQUEST['index'];
        if ($index) {
            $model = NID::model()->findByPk((int) $index);
        }

        if (!$model) {
            $model = new NID;
        }else{
            if($model->SubStatus!='New Item'){
                $this->redirect(array('nid'));
            }
        }

        if (isset($_POST['NID'])) {
            $model->attributes = $_POST['NID'];
            $new = $model->isNewRecord;
            if ($model->save()) {
                if ($new) {
                    $msg = '创建成功';
                } else {
                    $msg = '更新成功';
                }
            }
            if ($msg) {
                if($model->SubStatus=='New Item'){
                    $url = Yii::app()->createUrl('admin/NidUpdate', array('index' => $model->Index));
                }else{
                    $url = Yii::app()->createUrl('admin/nid');
                }
                header("Content-Type:text/html;charset=utf-8");
                echo '<script>alert("' . $msg . '");window.location.href="' . $url . '";</script>';
            }
        }
        
        $condition = new CDbCriteria();
        $condition->addCondition("Table_Name='Product'");
        $condition->addCondition("Field_Name='Category'");
        $condition->order = 'Field_Options asc';
        $classes = FieldOption::model()->findAll($condition);
        $data['classes'] = CHtml::listData($classes, 'Field_Options', 'Field_Options');
        unset($condition);
        unset($classes);

        if ($model->Category) {
            $condition = new CDbCriteria();
            $condition->addCondition("Bridge='" . $model->Category . "'");
            $condition->order = 'Field_Options asc';
            $subclasses = FieldOption::model()->findAll($condition);
            $data['subclasses'] = CHtml::listData($subclasses, 'Field_Options', 'Field_Options');
            unset($subclasses);
            unset($condition);
        }

        $this->render('nidDetail', array(
            'model' => $model,
            'data' => $data,
        ));
    }
    
}